import struct


def write_int(arg):
    data = struct.pack('!l', arg)
    return data


def read_int(arg):
    data = struct.unpack('!l', arg)
    return data


def get_byte(arg):
    data = struct.unpack('1B', arg)
    return data


def get_short(arg):
    data = struct.unpack('!h', arg)
    return data


def write_byte(arg):
    data = struct.pack('1B', arg)
    return data


def write_short(arg):
    data = struct.pack('!h', arg)
    return data


def write_string(arg):
    str_len = len(arg)
    fmt = '%ds' % str_len
    data = struct.pack(fmt, arg)
    return data


def get_only_pub_msg(topic):
    #  msg type
    data = write_byte(0)
    #  msg id
    data += write_int(0)
    #  topic len
    topic_len = len(topic)
    data += write_short(topic_len)
    #  topic
    data += write_string(topic)
    #  total_len
    total_len = len(data)
    head_len = write_short(total_len)
    msg_len = write_int(total_len)
    return (msg_len + head_len + data)


def get_sub_msg(topic):
    #  msg type
    data = write_byte(1)
    # msg id
    data += write_int(0)
    # topic len
    topic_len = len(topic)
    data += write_short(topic_len)
    # topic
    data += write_string(topic)
    # total_len
    total_len = len(data)
    head_len = write_short(total_len)
    msg_len = write_int(total_len)
    return msg_len+head_len+data


def get_unsub_msg(topic):
    # msg type
    data = write_byte(2)
    # msg id
    data += write_int(0)
    # topic len
    topic_len = len(topic)
    data += write_short(topic_len)
    # topic
    data += write_string(topic)
    # total_len
    total_len = len(data)
    head_len = write_short(total_len)
    msg_len = write_int(total_len)
    return (msg_len + head_len + data)


def get_pub_msg(topic, msg):
    # msg type
    data = write_byte(3)
    # msg id
    data += write_int(0)
    # topic len
    topic_len = len(topic)
    data += write_short(topic_len)
    # topic
    data += write_string(topic)
    # total_len
    head_len = len(data)
    # msg
    data += write_string(msg)
    # total_len
    head_len = write_short(head_len)
    msg_len = len(data)
    msg_len = write_int(msg_len)
    return (msg_len + head_len + data)

def get_heartbeat_msg(topic):
    # msg type
    data = write_byte(5)
    # msg id
    data += write_int(0)
    # topic len
    topic_len = len(topic)
    data += write_short(topic_len)
    # topic
    data += write_string(topic)
    # total_len
    total_len = len(data)
    head_len = write_short(total_len)
    msg_len = write_int(total_len)
    return (msg_len + head_len + data)
